package com.me.seckill.consumer;

import com.me.seckill.config.RabbitMQConfig;
import com.me.seckill.pojo.Stock;
import com.me.seckill.service.OrderService;
import com.rabbitmq.client.Channel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.amqp.support.AmqpHeaders;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;
import org.springframework.stereotype.Component;

import java.io.IOException;

/**
 * RabbitMQ 异步生成订单
 *
 * @author ME
 * @date 2021/7/9
 */
@Component
public class SeckillConsumer {

    private static final Logger log = LoggerFactory.getLogger(SeckillConsumer.class);

    @Autowired
    private OrderService orderService;

    /**
     * 秒杀队列中的消息处理器
     *
     * @param message   带泛型的消息对象，包含 headers、payload
     * @param channel 消息通道，用来手动 ack
     */
    @RabbitListener(queues = RabbitMQConfig.SECKILL_QUEUE)
    public void receiveSeckill(Message<Stock> message, Channel channel) {
        try {
            // System.out.println(message.getPayload());
            // System.out.println(message.getHeaders().get(AmqpHeaders.RECEIVED_ROUTING_KEY));
            System.out.println(message.getHeaders().get(AmqpHeaders.REDELIVERED));// 再次投递的消息
            orderService.createOrder(message.getPayload());

            Long deliveryTag = (Long) message.getHeaders().get(AmqpHeaders.DELIVERY_TAG);
            if (1 == 1) {
                // channel.basicNack(deliveryTag, false, true);
                throw new RuntimeException("233333");
            }
            // 消息投递序号、是否批量确认小于当前序号的消息
            channel.basicAck(deliveryTag, false);
        } catch (IOException e) {
            System.out.println(message.getHeaders().get(AmqpHeaders.REDELIVERED));
            // if (message.getMessageProperties().getRedelivered()) {
            //     log.error("消息已重复处理失败,拒绝再次接收...");
            //     channel.basicReject(message.getMessageProperties().getDeliveryTag(), false); // 拒绝消息
            // } else {
            //     log.error("消息即将再次返回队列处理...");
            //     channel.basicNack(message.getMessageProperties().getDeliveryTag(), false, true);
            // }
        }
    }

}
